package com.atguigu.springcloud.service.impl;

import cn.hutool.core.util.IdUtil;
import com.atguigu.springcloud.service.PaymentService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author Tu
 * @date 2023/6/11 18:13
 */
@Service
public class PaymentServiceImpl implements PaymentService {

    @Override
    public String paymentInfoSuccess(Integer id) {
        return "支付信息成功接口，线程池：" + Thread.currentThread().getName() + "，id：" + id;
    }

    /**
     * execution.isolation.thread.timeoutInMilliseconds
     * 设置默认调用时间，超过即为超时降级处理
     *
     * @param id
     * @return
     */
    @Override
    @HystrixCommand(fallbackMethod = "paymentInfoErrorHandler", commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")})
    public String paymentInfoError(Integer id) {
        //异常会直接降级处理
        //int age = 10/0;
        //休眠
        int lineNum = 5;
        try {
            TimeUnit.SECONDS.sleep(lineNum);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "支付信息接口调用时间过长，线程池：" + Thread.currentThread().getName() + "，时间：" + lineNum + "秒";
    }

    public String paymentInfoErrorHandler(Integer id) {
        return "支付信息接口调用超时，线程池：" + Thread.currentThread().getName() + "，系统繁忙，请稍后再试，id：" + id;
    }

    @Override
    @HystrixCommand(fallbackMethod = "paymentCircuitFallBack", commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled", value = "true"),//是否开启断路器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),//请求次数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"),//时间窗口期（一段时间后转换保险丝状态）
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60"),//失败率达到百分之多少熔断
    }
    )
    public String paymentCircuitBreaker(Integer id) {
        //断路器有三种状态，关闭，开启，半开状态
        //输入负数模式失败场景，当错误次数过多时（错误百分比），会启动服务熔断，熔断期间的请求会直接调用降级（即使请求是正确的）
        //在熔断期间，断路器为开启状态。窗口期过了之后会为半开状态，其实下一个请求调用会判断成功和失败，成功则关闭，不成功继续熔断
        if (id < 0) {
            throw new RuntimeException("id不能为负数");
        }
        String serialNumber = IdUtil.simpleUUID();
        return Thread.currentThread().getName() + "\t" + "调用成功，流水号：" + serialNumber;
    }

    /**
     * 服务熔断-降级处理
     *
     * @param id
     * @return
     */
    public String paymentCircuitFallBack(Integer id) {
        return "id不能为负数，请稍后再试，id：" + id;
    }

}
